//
//  GesturePassword.m
//  DaoZiJinFu
//
//  Created by woker on 16/8/16.
//  Copyright © 2016年 iwoker. All rights reserved.
//

#import "GesturePassword.h"
#import "ForgetGesturePwd.h"
#import "DZPassView.h"
@interface GesturePassword ()

@property (nonatomic,strong)NSMutableArray *buttonArr;//全部手势按键的数组
@property (nonatomic,strong)NSMutableArray *selectorArr;//选中手势按键的数组
@property (nonatomic,assign)CGPoint startPoint;//记录开始选中的按键坐标
@property (nonatomic,assign)CGPoint endPoint;//记录结束时的手势坐标
@property (nonatomic,strong)UIImageView *imageView;//画图所需

@property (nonatomic,strong)UILabel *titleLabel;
@property (nonatomic,strong)UIButton *botBtn;
@property (nonatomic,strong)UILabel *numLab;

@property (nonatomic,strong)NSMutableString *firstOrderStr;//第一次密码
@property (nonatomic,strong)NSMutableString *secondOrderStr;//第二次密码
@property (nonatomic,assign)NSInteger settingType;//1，第一次设置密码  2，确认密码

@property (nonatomic,assign)NSInteger unlockCount;

@property (nonatomic,strong)ForgetGesturePwd *forgetGestureView;

@property (strong, nonatomic) DZPassView *imageV;

@end

@implementation GesturePassword

-(NSMutableArray *)selectorArr
{
    if (!_selectorArr) {
        _selectorArr = [[NSMutableArray alloc]init];
    }
    
    return _selectorArr;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor whiteColor];
//    self.navigationItem.hidesBackButton = YES;
    _firstOrderStr = [NSMutableString string];
    _secondOrderStr = [NSMutableString string];
    _settingType = 1;
    _unlockCount = 5;
    self.view.backgroundColor = [UIColor whiteColor];
    NSLog(@"PWD: %@",userValue(GESTUREPWDNUM));
    
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(forgetGestureToLogin) name:@"forgetGestureToLogin" object:nil];
    
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(loginSuccess) name:@"loginSuccess" object:nil];
    
    if (!_buttonArr) {
        _buttonArr = [[NSMutableArray alloc]initWithCapacity:9];
    }
    
    self.imageView = [[UIImageView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT)];
    self.imageV = [[DZPassView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT)];
    self.imageV.backgroundColor = [UIColor clearColor];
    [self.view addSubview:self.imageV];
    //[self.view addSubview:self.imageView];
    
    CGFloat insetMargin = (SCREEN_WIDTH)/4.0;
    
    CGFloat appHeight = SCREEN_HEIGHT-64;
    
    for (int i=0; i<3; i++) {
        for (int j=0; j<3; j++) {
            UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
            btn.tag = i*3+(j+1);
            btn.frame = CGRectMake(insetMargin*(j+1)-30, (appHeight-(insetMargin*2+60))/2.0+insetMargin*i+64, 60, 60);
            [btn setImage:[UIImage imageNamed:@"未点"] forState:UIControlStateNormal];
            [btn setImage:[UIImage imageNamed:@"点击"] forState:UIControlStateHighlighted];
            [btn setImage:[UIImage imageNamed:@"手势错误"] forState:UIControlStateSelected];
            btn.userInteractionEnabled = NO;
            [self.buttonArr addObject:btn];
            [self.imageV addSubview:btn];
        }
    }
    
    self.startPoint = CGPointMake(0, 0);
    self.endPoint = CGPointMake(0, 0);
    
    _titleLabel = [[UILabel alloc] init];
    _titleLabel.font = [UIFont systemFontOfSize:16];
    _titleLabel.textColor = DEFAULTCOLOR;
    [self.view addSubview:_titleLabel];
    [_titleLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.view.mas_top).offset((appHeight-(insetMargin*2+60))/4.0-11+64);
        make.centerX.equalTo(self.view.mas_centerX);
    }];
    
    _numLab = [[UILabel alloc]init];
    _numLab.font = [UIFont systemFontOfSize:16];
    _numLab.textColor = DEFAULTCOLOR;
//    _numLab.text = userValue(GESTUREPWDNUM);
    [self.view addSubview:_numLab];
    [_numLab mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(self.view.mas_centerX);
        make.top.equalTo(_titleLabel.mas_bottom).offset(8);
    }];
    
    _botBtn = [[UIButton alloc] init];
    _botBtn.titleLabel.font = [UIFont systemFontOfSize:14];
    [_botBtn setTitleColor:GRAYCOLOR forState:UIControlStateNormal];
    [_botBtn addTarget:self action:@selector(botBtnClick) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:_botBtn];
    [_botBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(self.view.mas_centerX);
        make.top.equalTo(self.view.mas_top).offset((3*appHeight+(insetMargin*2+60))/4.0+64-11);
    }];
    
    if (_gestureType == GestureTypeUnlock) {
        [self setupTitleView:@"手势密码登录"];
        _titleLabel.text = @"请输入手势密码";
        [_botBtn setTitle:@"忘记手势密码 >" forState:UIControlStateNormal];
    } else {
        [self leftButton:nil];
        [self setupTitleView:@"设置手势密码"];
        _titleLabel.text = @"请输入手势密码";
        [_botBtn setTitle:@"暂不设置，进入理财 >" forState:UIControlStateNormal];
    }
}

- (void)botBtnClick {
    NSLog(@"click");
    if (_gestureType == GestureTypeUnlock) {
        [ForgetGesturePwd showView:THISVIEW];
    } else {
        if ([userValue(HAVEGESTUREPWD) integerValue] != 0 || [userValue(HAVEGESTUREPWD) integerValue] != 3) {
            [theUser setObject:[NSNumber numberWithInteger:2] forKey:HAVEGESTUREPWD];
        }
        [self.navigationController popToRootViewControllerAnimated:YES];
        [[NSNotificationCenter defaultCenter]postNotificationName:@"loginSuccess" object:self];
    }
}

- (void)forgetGestureToLogin {
    [theUser setObject:[NSNumber numberWithInteger:3] forKey:HAVEGESTUREPWD];
    if (userValue(HOSTTEL)) {
        LoginViewController *login = [[LoginViewController alloc] init];
        login.telNum = userValue(HOSTTEL);
        [self.navigationController pushViewController:login animated:YES];
    } else {
        RegisterViewController *join = [[RegisterViewController alloc] init];
        [self.navigationController pushViewController:join animated:YES];
    }
}

- (void)loginSuccess {
    [self.navigationController dismissViewControllerAnimated:YES completion:^{
        
    }];
}
//开始手势
-(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
    UITouch *touch = [touches anyObject];//保存所有触摸事件
    if (touch) {
        for (UIButton *btn in self.buttonArr) {
            CGPoint po = [touch locationInView:btn];//记录按键坐标
            if ([btn pointInside:po withEvent:nil]) {//判断按键坐标是否在手势开始范围内,是则为选中的开始按键
                [self.selectorArr addObject:btn];
                btn.highlighted = YES;
                self.startPoint = btn.center;//保存起始坐标
            }
        }
    }
}

//移动中触发，画线过程中会一直调用画线方法
-(void)touchesMoved:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
    UITouch *touch = [touches anyObject];
    if (touch) {
        self.endPoint = [touch locationInView:self.imageView];
        for (UIButton *btn in self.buttonArr) {
            CGPoint po = [touch locationInView:btn];
            if ([btn pointInside:po withEvent:nil]) {
                
                BOOL isAdd = YES;//记录是否为重复按键
                for (UIButton *seBtn in self.selectorArr) {
                    if (seBtn == btn) {
                        isAdd = NO;//已经是选中过的按键，不再重复添加
                        break;
                    }
                }
                if (isAdd) {//未添加的选中按键，添加并修改状态
                    [self.selectorArr addObject:btn];
                    btn.highlighted = YES;
                }
                
                if (self.selectorArr.count == 1 && self.startPoint.x == 0 && self.startPoint.y == 0) {
                    UIButton *firstBtn = self.selectorArr[0];
                    CGPoint startPt = firstBtn.center;
                    self.startPoint = startPt;
                }
            }
        }
    }
    CGPoint point = [touch locationInView:_imageV];
    _imageV.currtPoint = point;
    _imageV.style = 1;
    _imageV.selectArr = _selectorArr;
    [_imageV  setNeedsDisplay];
}
//手势结束触发
-(void)touchesEnded:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
    NSInteger errorFlag = 0;
    if (self.selectorArr.count == 0) {
    }else {
        if (_gestureType == GestureTypeUnlock) {
            if (_unlockCount == 0) {
                _numLab.text = @"解锁失败，您需要重新登录";
                [self forgetGestureToLogin];
            } else {
                for (UIButton *btn in self.selectorArr) {
                    [_firstOrderStr appendFormat:@"%ld",btn.tag];
                }
                if ([_firstOrderStr isEqualToString:userValue(GESTUREPWDNUM)]) {
                    [self dismissViewControllerAnimated:YES completion:^{
                    }];
                } else {
                    errorFlag = 1;
                    _unlockCount--;
                    if (_unlockCount == 0) {
                        _numLab.text = @"解锁失败，您需要重新登录";
                        [self forgetGestureToLogin];
                    } else {
                        _numLab.text = [NSString stringWithFormat:@"密码错误，剩余%ld次机会",_unlockCount];
                    }
                }
                _firstOrderStr = [NSMutableString stringWithFormat:@""];
            }
        } else {
            if (self.selectorArr.count < 4 && self.selectorArr.count > 0) {
                _numLab.text = @"至少连接4个点\n请重新绘制";
                errorFlag = 1;
            } else if (self.selectorArr.count >= 4) {
                for (UIButton *btn in self.selectorArr) {
                    NSLog(@"%ld",btn.tag);
                    if (_settingType == 1) {
                        [_firstOrderStr appendFormat:@"%ld",btn.tag];
                    } else {
                        [_secondOrderStr appendFormat:@"%ld",btn.tag];
                    }
                }
                
                if (_settingType == 1) {
                    _settingType = 2;
                    _numLab.text = @"请再次绘制解锁图案";
                } else {
                    if ([_firstOrderStr isEqualToString:_secondOrderStr]) {
                        NSLog(@"vc:%@",self.navigationController.viewControllers);
                        JSSHOW(@"设置成功");
                        [theUser setObject:[NSNumber numberWithInteger:1] forKey:HAVEGESTUREPWD];
                        [theUser setObject:_firstOrderStr forKey:GESTUREPWDNUM];
                        [self.navigationController popToRootViewControllerAnimated:YES];
                        [[NSNotificationCenter defaultCenter]postNotificationName:@"setGestureSuccess" object:self];
                        [[NSNotificationCenter defaultCenter]postNotificationName:@"loginSuccess" object:self];
                        
                    } else {
                        errorFlag = 1;
                        _numLab.text = @"与首次绘制图案不一致请重新绘制";
                        _secondOrderStr = [NSMutableString stringWithString:@""];
                    }
                }
            } else {
                ;
            }
        }
    }
    if (errorFlag == 1) {
        for (UIButton *btn in self.selectorArr) {
            btn.highlighted = NO;
            btn.selected = YES;
        }
        _imageV.selectArr = _selectorArr;
        _imageV.style = 0;
        [_imageV setNeedsDisplay];
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            self.selectorArr = nil;
            self.imageView.image = nil;
            for (UIButton *btn in self.buttonArr) {
                btn.highlighted = NO;
                btn.selected = NO;
            }
            self.startPoint = CGPointMake(0, 0);
            self.endPoint = CGPointMake(0, 0);
            _imageV.selectArr = @[];
            [_imageV setNeedsDisplay];
        });
    }else {
        self.selectorArr = nil;
        self.imageView.image = nil;
        for (UIButton *btn in self.buttonArr) {
            btn.highlighted = NO;
        }
        self.startPoint = CGPointMake(0, 0);
        self.endPoint = CGPointMake(0, 0);
        _imageV.selectArr = @[];
        _imageV.style = 1;
        [_imageV setNeedsDisplay];
    }
}



- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
  
}

@end
